import requests
import matplotlib.pyplot as plt
import pandas as pd
import re
import os
music164_url = 'https://music.163.com/discover/toplist?id=3778678'
headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36"
}

responses = requests.get(url=music164_url, headers=headers)
responses.encoding = responses.apparent_encoding
html_data = re.findall(r'<li><a href="/song\?id=(\d+)">(.*?)</a>', responses.text)
# print(html_data)
filename = 'D:\Workspaces\study\python\music'
if not os.path.exists(filename):
    os.mkdir(filename)

for mun_id, title in html_data:
    music_url = f'http://music.163.com/song/media/outer/url?id={mun_id}.mp3'
    music_content = requests.get(music_url, headers=headers).content
    with open(filename + '/' + title + '.mp3', mode='wb') as f:
        f.write(music_content)
    print(mun_id, title)
print("-----------------------------------------------------------------------------")
pd.DataFrame(html_data).to_csv('D:\Workspaces\study\python\music\网易云.csv')
print("-----------------------------------------------------------------------------")
